<template>
  <!-- 信息展示框 -->
  <div class="info-box">
    <!-- 修改信息 -->
    <div class="my-info">
      <Form
        ref="form"
        :model="form"
        :rules="ruleCustom"
        :label-width="80"
        label-position="left"
      >
        <FormItem label="头像">
          <div class="head" v-if="flag" @click="handleShow">
            <Avatar v-if="form.face" style="background-color: #cccccc" :src="form.face" size="64" />
            <Avatar v-else icon="ios-person" size="64" />
          </div>
          <div class="head" v-else>
            <Avatar v-if="form.face" style="background-color: #cccccc" :src="form.face" size="64" />
            <Avatar v-else icon="ios-person" size="64" />
          </div>
        </FormItem>
        <FormItem label="昵称:" prop="nickName">
          <Input type="text" v-model="form.nickName" v-if="flag"></Input>
          <span v-else>{{ form.nickName }}</span>
        </FormItem>
        <FormItem label="性别:" prop="sex">
          <RadioGroup v-model="form.sex" v-if="flag">
            <Radio label="1">
              <span>男</span>
            </Radio>
            <Radio label="0">
              <span>女</span>
            </Radio>
          </RadioGroup>
          <span v-else>{{ form.sex === "1" ? "男" : "女" }}</span>
        </FormItem>
        <FormItem label="出生年月:" prop="birthday">
          <DatePicker
            type="date"
            style="width: 100%"
            v-model="form.birthday"
            placeholder="请选择出生时间"
            v-if="flag"
          ></DatePicker>
          <span v-else>{{ form.birthday }}</span>
        </FormItem>
        <FormItem label="身高:" prop="height">
          <InputNumber
            :max="300"
            :min="1"
            v-model="form.height"
            @on-blur="heiWeiChange"
            @on-keyup="form.height = form.height.replace(/[^\d.]/g, '')"
            style="width: 90%"
            v-if="flag"
          ></InputNumber>
          <span v-else>{{ form.height }}</span>
          <span class="unit">cm</span>
        </FormItem>
        <FormItem label="体重:" prop="sex">
          <InputNumber
            :max="500"
            :min="1"
            v-model="form.weight"
            @on-blur="heiWeiChange"
            @on-keyup="form.weight = form.weight.replace(/[^\d.]/g, '')"
            style="width: 90%"
            v-if="flag"
          >
          </InputNumber>
          <span v-else>{{ form.weight }}</span>
          <span class="unit">kg</span>
        </FormItem>

        <FormItem label="运动目的:" prop="targetType">
          <CheckboxGroup v-model="form.targetType" v-if="flag">
            <Checkbox label="1000003">增肌 </Checkbox>
            <Checkbox label="1000002">减脂 </Checkbox>
            <Checkbox label="1000001">塑性 </Checkbox>
          </CheckboxGroup>
          <div v-else>
            <span
              v-for="(v, i) in form.targetType"
              :key="i"
              style="margin-right: calc(14 / 1920 * 100vw)"
            >
              <span v-if="v == '1000003'">增肌</span>
              <span v-if="v == '1000002'">减脂</span>
              <span v-if="v == '1000001'">塑性</span>
            </span>
          </div>
        </FormItem>
        <FormItem label="您的体型:" prop="weight">
          <span>{{ weiText }}</span>
        </FormItem>
        <FormItem label="bmi指数:" prop="bmi">
          <span>{{ form.bmi }}</span>
        </FormItem>
        <FormItem label="健康建议:" prop="siteName">
          <span> {{ siteText }} </span>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="edit()" v-if="!flag"> 修改</Button>
          <Button type="primary" @click="save()" v-else> 确定</Button>
          <Button style="margin-left: 8px" @click="cancel()">取消</Button>
        </FormItem>
      </Form>
    </div>
    <!-- 头像弹框 -->
    <Modal
      v-model="headModelShow"
      title="头像设置"
      @on-ok="ok"
      @on-cancel="headModelShow = false"
    >
      <div class="head-info">
        <Avatar v-if="modelHead" :src="modelHead" size="64" />
        <Avatar v-else icon="ios-person" size="64" />
        <Upload
          multiple
          ref="upload"
          :before-upload="handleBeforeUpload"
          action="//jsonplaceholder.typicode.com/posts/"
        >
          <Button icon="ios-camera">重新上传</Button>
        </Upload>
      </div>

      <div slot="footer">
        <Button type="primary" size="large" long @click="saveHead">保存</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { onLoadFile } from "@/api/otwoo.js";
import bus from '@/libs/bus.js'
import { edituser } from "@/api/set.js";
import { userInfo } from "../../api/otwoo.js";
import storage from '../../plugins/storage.js';
export default {
  data() {
    return {
      modelHead: "",
      headModelShow: false,
      flag: false, //信息修改判断
      form: {
        face: null, //头像
        nickName: null,
        birthday: null,
        sex: "0",
        height: null,
        weight: null,
        targetType: [],
        bmi: null,
      },
      ruleCustom: {},

      userInfo: {},
      uploadList: [],
      weiText: "",
      siteText: "",
    };
  },
  mounted() {
    this.getInfo();
  },
  methods: {
    heiWeiChange() {
      if (this.form.height && this.form.weight) {
        let w = parseFloat(this.form.weight);
        let h = parseFloat(this.form.height) / 100;
        this.form.bmi = parseFloat(w / (h * h), 2).toFixed(2);
      } else {
        this.form.bmi = "";
      }
      this.siteText = this.switchText(this.form.bmi);
      this.weiText = this.bodyTypeText(this.form.bmi);
    },
    bodyTypeText(n) {
      let label = "";
      if (n > 0 && n <= 18.4) label = "消瘦";
      if (n >= 18.5 && n <= 23.9) label = "正常";
      if (n >= 24 && n <= 27.9) label = "超重";
      if (n >= 28 && n <= 31.9) label = "Ⅰ型肥胖";
      if (n >= 32 && n <= 35.9) label = "Ⅱ型肥胖";
      if (n >= 36) label = "Ⅲ型肥胖";
      return label;
    },
    switchText(n) {
      let label = "";
      if (n > 0 && n <= 18.4)
        label = "建议您通过力量练习和多增加营养摄入，增加体重";
      if (n >= 18.5 && n <= 23.9)
        label = "建议您继续保持良好的饮食习惯和锻炼习惯，保持正常体型";
      if (n >= 24)
        label =
          "建议您适当控制饮食摄入，增加快走、慢跑、球类等有氧运动，减少身体脂肪含量";
      return label;
    },
    //获取用户信息
    getInfo() {
      userInfo().then((res) => {
        if (res.success) {
          bus.$emit('upUserInfo')
          storage.setItem("userInfo", JSON.stringify(res.result));
          const obj = res.result || {};
          Object.keys(this.form).map((key) => {
            this.form[key] = obj[key];
          });
          this.form.targetType = obj.targetType.split(",") || [];
          let num = obj.weight / (((obj.height / 100) * obj.height) / 100);
          this.form.bmi = Number(num.toFixed(2));
          this.heiWeiChange();
        }
      });
    },
    edit() {
      this.flag = !this.flag;
    },
    save() {
      const params = Object.assign({}, this.form);
      params.targetType = this.form.targetType.join(",");
      if (params.birthday) {
        params.birthday = new Date(params.birthday).format("yyyy-MM-dd");
      }
      //   发请求;
      edituser(params).then((res) => {
        if (res.message == "success") {
          localStorage.setItem("userInfo", JSON.stringify(res.result));
          this.flag = false;
          this.getInfo();
          this.$Message.success("修改成功！");
        } else {
          this.$Message.error(res.message);
        }
      });
    },
    cancel() {
      this.flag = false;
    },

    handleShow() {
      this.modelHead = this.form.face;
      this.headModelShow = true;
    },
    // 保存头像
    saveHead() {
      this.form.face = this.modelHead;
      this.headModelShow = false;
    },
    // 关闭弹框
    ok() {
      this.headModelShow = false;
    },
    handleBeforeUpload(file) {
      // console.log(file.size);
      // if (file.size > 20 * 1024 * 1024) {
      //   return this.$Message.error("文件大小不得超过20M");
      // }
      const check = this.uploadList.length < 2;
      if (!check) {
        this.$Notice.warning({
          title: "最多只能上传一张头像",
        });
      }
      this.onLoadFile(file);
      return false;
    },
    // 上传图片
    onLoadFile(file) {
      var formData = new FormData();
      formData.append("file", file);
      onLoadFile(formData).then((res) => {
        console.log(res);
        if (res.code == 200) {
          this.modelHead = res.result;
        }
      });
    },
  },
  components: {},
};
</script>
<style lang="scss" scoped>
.info-box {
  width: calc(1650 / 1920 * 100vw);
  background: #fff;
  position: absolute;
  top: calc(288 / 1920 * 100vw);
  left: calc(240 / 1920 * 100vw);
  padding: calc(10 / 1920 * 100vw) calc(40 / 1920 * 100vw)
    calc(40 / 1920 * 100vw);
  .my-info {
    width: 40%;
    :deep(.ivu-form-item) {
      margin-bottom: 16px;
    }
    .unit {
      display: inline-flex;
      width: 10%;
      justify-content: center;
      align-items: center;
      color: #676767;
    }
  }
}
.head-info {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  :deep(.ivu-btn) {
    margin-top: 10px;
  }
}
</style>
